#include "app_message.h"
#include "app_com.h"
#include "cJSON.h"
#include "log.h"
#include "string.h"

char *app_message_bytes_to_json(char *data, int data_len)
{
    // 从字节数组中提取连接类型,设备id,消息体
    char conn_type = data[0];
    int id_len = data[1];
    int msg_len = data[2];
    char id[id_len];
    char msg[msg_len];
    memcpy(id, data + 3, id_len);
    memcpy(msg, data + 3 + id_len, msg_len);
    // id和消息体需要把字节转换为两位16进制字符串
    char *id_hex = app_com_bytes2hexstr(id, id_len);
    char *msg_hex = app_com_bytes2hexstr(msg, msg_len);
    // 创建JSON对象把连接类型,id,消息体放入 JSON对象中
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json_str = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return json_str;
}

int app_message_json_to_bytes(char *json, char *data, int data_len)
{
    // 把json字符串转为JSON对象,提取连接类型,设备id,消息体
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("json parse error");
        return -1;
    }
    cJSON *conn_type_json = cJSON_GetObjectItem(root, "conn_type");
    cJSON *id_json = cJSON_GetObjectItem(root, "id");
    cJSON *msg_json = cJSON_GetObjectItem(root, "msg");
    if (conn_type_json == NULL || id_json == NULL || msg_json == NULL)
    {
        log_error("json parse error");
        return -1;
    }
    int conn_type = conn_type_json->valueint;
    char *id_hexstr = id_json->valuestring;
    char *msg_hexstr = msg_json->valuestring;
    // 把id和消息体转为字节数组
    int id_len = strlen(id_hexstr) / 2;   // id字节的长度
    int msg_len = strlen(msg_hexstr) / 2; // msg字节的长度
    char id[id_len];
    char msg[msg_len];
    id_len = app_com_hexstr2bytes(id_hexstr, id, id_len);
    msg_len = app_com_hexstr2bytes(msg_hexstr, msg, msg_len);
    // 把连接类型,id,消息体放入字节数组中
    data[0] = conn_type;
    data[1] = id_len;
    data[2] = msg_len;
    memcpy(data + 3, id, id_len);
    memcpy(data + 3 + id_len, msg, msg_len);
    return 3 + id_len + msg_len;
}
